require('styles/TextBox.less')
import React from 'react'

class TextBox extends React.Component{
  constructor(props){
    super(props)
  }
  render(){
    return (
      <div className="cpn-text-box">
        {this.renderInputArea()}
        {this.renderCounter()}
      </div>
    )
  }
  renderInputArea(){
    return React.createElement(
      this.props.mutiline ? 'textarea' : 'input',
      {
        ref: 'inputArea',
        value: this.props.value,
        onChange: this.handleChange.bind(this)
      }
    )
  }
  handleChange(evt){
    let handler = this.props.onChange
    handler && handler(evt.target.value)
  }
  renderCounter(){
    if(this.props.showCounter){
      let {limit} = this.props
      let inputLength = this.props.value.length
      let classes = ['counter']
      if(inputLength > limit)
        classes.push('exceed')
      return (
        <div className={classes.join(' ')}>
          {inputLength}{limit ? '/'+limit : ''}
        </div>
      )
    }
  }
  componentDidMount() {
    if(this.props.autoFocus)
      (false || this.refs.inputArea).focus()
  }
}

TextBox.propTypes = {
  mutiline: React.PropTypes.bool,
  showCounter: React.PropTypes.bool,
  limit: React.PropTypes.number,
  defaultValue: React.PropTypes.string,
  value: React.PropTypes.string.isRequired
}

export default TextBox
